package com.ruoyi.web.controller.mqtt;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.AirDetails;
import com.ruoyi.system.service.IAirDetailsService;
import com.ruoyi.web.controller.gatewayManagement.AirDetailsController;
import com.ruoyi.web.controller.websocket.MyWebSocketHandler;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Component
public class PushCallback implements MqttCallback {
    private static final Logger logger = LoggerFactory.getLogger(MqttPushClient.class);

    @Autowired
    private MqttConfig mqttConfig;

    @Autowired
    private IAirDetailsService airDetailsService;

    @Autowired
    private AirDetailsController airDetailsController;

    private static MqttClient client;

    public  static PushCallback PushCallback ;

    @PostConstruct            //通过@PostConstruct实现初始化bean之前进行的操作
    public void init() {
        System.out.println("初始化");
        PushCallback = this;
    }

    @Override
    public void connectionLost(Throwable throwable) {
        // 连接丢失后，一般在这里面进行重连
        logger.info("连接断开，可以做重连");
//        System.out.println(throwable);
        if (client == null || !client.isConnected()) {
            mqttConfig.getMqttPushClient();
        }
    }

    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
        // subscribe后得到的消息会执行到这里面
        logger.info("接收消息主题 : " + topic);
        logger.info("接收消息Qos : " + mqttMessage.getQos());
        logger.info("接收消息内容 : " + new String(mqttMessage.getPayload()));
        //处理数据
        try{
            receive(topic, new String(mqttMessage.getPayload()));
        }catch (Exception e){
            logger.info(topic+"主题消息解析异常");
        }
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        logger.info("发布消息成功");
        //发布消息成功之后 才会调用这里
        logger.info("deliveryComplete---------" + iMqttDeliveryToken.isComplete());
    }

    //处理接收到的数据
    public void receive(String topic,String info){
        JSONObject jsonObject=JSONObject.parseObject(info);
        System.out.println("主题："+topic+"-----接收的数据-------"+jsonObject);
        switch (topic){
            case "tent_event":    //  设备 上电
                String time = DateUtils.getTime();
                AirDetails airDetails = new AirDetails();
                airDetails.setMainboardId(jsonObject.getString("id"));
                airDetails.setMainEvent(jsonObject.getString("event"));
                airDetails.setVersion(jsonObject.getString("version"));
                airDetails.setTime(time);
                airDetails.setPowerOnStatus("0");
                airDetailsController.addDevice(airDetails);

                MyWebSocketHandler.broadcast( "设备上电："+ jsonObject.getString("id"));
                break;
            case "tent_will":    // 网关遗嘱
                String mainboard_id = jsonObject.getString("id");
                AirDetails air_will = new AirDetails();
                air_will.setPowerOnStatus("1");
                air_will.setMainboardId(mainboard_id);
                airDetailsController.updateAirStatus(air_will);
                System.out.println("----网关遗嘱----"+ mainboard_id);

                MyWebSocketHandler.broadcast( "网关遗嘱："+ mainboard_id);
                break;
            case "tent_response":      // 配置服务器响应
                String status = jsonObject.getString("status");
                String msg_id = jsonObject.getString("msg_id");
                String id = jsonObject.getString("id");
//                LocalDate today = LocalDate.now();
//                // 直接获取月份和日期
//                int month = today.getMonthValue();
//                int day = today.getDayOfMonth();

                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M-d HH:mm");
                String formattedTime = LocalDateTime.now().format(formatter);

                switch (msg_id){
                    case "1234":      // 服务器配置
                        AirDetails a = new AirDetails();
                        a.setMainboardId(id);
                        a.setStatus("已配置"+ formattedTime);
                        airDetailsController.updateAirStatus(a);

                        MyWebSocketHandler.broadcast( "配置成功："+ id);
                        break;
                    case "123":     // OTA 升级
                        AirDetails air_ota = new AirDetails();
                        air_ota.setMainboardId(id);
                        air_ota.setNetworkInfo("升级成功"+ formattedTime);
                        airDetailsController.updateAirStatus(air_ota);

                        MyWebSocketHandler.broadcast( "升级成功："+ id);
                        break;
                    default:
                        break;
                }
                break;
            default:
                break;

        }
    }

}
